package com.itmk.web.teacher.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itmk.web.teacher.entity.Teacher;
import com.itmk.web.teacher.entity.TeacherParm;
import com.itmk.web.teacher.mapper.TeacherMapper;
import com.itmk.web.teacher.service.TeacherService;
import com.itmk.web.teacher_role.entity.TeacherRole;
import com.itmk.web.teacher_role.service.TeacherRoleService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * @Author java实战基地
 * @Version 3501754007
 */
@Service
public class TeacherServiceImpl extends ServiceImpl<TeacherMapper, Teacher> implements TeacherService {
    @Autowired
    private TeacherRoleService teacherRoleService;

    @Override
    public IPage<Teacher> getList(TeacherParm parm) {
        //构造分页对象
        IPage<Teacher> page = new Page<>();
        page.setSize(parm.getPageSize());
        page.setCurrent(parm.getCurrentPage());
        //构造查询条件
        QueryWrapper<Teacher> query = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(parm.getTeacherName())){
            query.lambda().like(Teacher::getTeacherName,parm.getTeacherName());
        }
        return this.baseMapper.selectPage(page,query);
    }

    @Override
    @Transactional
    public void addTeacher(Teacher teacher) {
        int insert = this.baseMapper.insert(teacher);
        if(insert >0){
            //设置教师角色
            TeacherRole teacherRole = new TeacherRole();
            teacherRole.setTeacherId(teacher.getTeacherId());
            teacherRole.setRoleId(teacher.getRoleId());
            teacherRoleService.save(teacherRole);
        }
    }

    @Override
    @Transactional
    public void editTeacher(Teacher teacher) {
        int i = this.baseMapper.updateById(teacher);
        if(i >0){
            //删除原来角色
            QueryWrapper<TeacherRole> query = new QueryWrapper<>();
            query.lambda().eq(TeacherRole::getTeacherId,teacher.getTeacherId());
            teacherRoleService.remove(query);
            //设置教师角色
            TeacherRole teacherRole = new TeacherRole();
            teacherRole.setTeacherId(teacher.getTeacherId());
            teacherRole.setRoleId(teacher.getRoleId());
            teacherRoleService.save(teacherRole);
        }
    }

    @Override
    @Transactional
    public void deleteTeacher(Long teacherId) {
        int i = this.baseMapper.deleteById(teacherId);
        if(i>0){
            QueryWrapper<TeacherRole> query = new QueryWrapper<>();
            query.lambda().eq(TeacherRole::getTeacherId,teacherId);
            teacherRoleService.remove(query);
        }
    }
}
